/*
 * Copyright 2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.influxdb;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.influxdb.annotation.Measurement;
import org.influxdb.dto.Point;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.TimeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.influxdb.json.JSON;

public class ConverterImpl<T> implements Converter<T> {

	private final Class<T> measurementClass;
	private final Map<String, ColumnMeta> columnMap = new HashMap<>();
	private ColumnMeta timeColumn;
	private final String measurementName;
	private TimeUnit timeUnit = TimeUnit.MILLISECONDS;

	public ConverterImpl(Class<T> measurementClass) {
		this.measurementClass = measurementClass;
		Measurement measurement = measurement();
		this.measurementName = measurementName(measurement);
		if (measurement != null) {
			this.timeUnit = measurement.timeUnit();
		}
		List<Field> fields = ConverterUtils.getFields(measurementClass);
		for (Field field : fields) {
			ColumnMeta meta = ColumnMeta.of(field, BeanUtils.getPropertyDescriptor(measurementClass, field.getName()));
			columnMap.put(meta.getName(), meta);
			if (meta.isTime()) {
				timeColumn = meta;
			}
			if (meta.isTime() && timeUnit == null) {
				timeUnit = meta.getTimeUnit();
			}
		}
	}

	private String measurementName(Measurement measurement) {
		if (measurement == null) {
			return measurementClass.getSimpleName();
		}
		String measurementName = measurement.name();
		if (ConverterUtils.isBlank(measurementName)) {
			measurementName = measurementClass.getSimpleName();
		}
		return measurementName;
	}

	private Measurement measurement() {
		Class<?> clazz = measurementClass;
		while (clazz != null) {
			Measurement annotation = (Measurement) clazz.getAnnotation(Measurement.class);
			if (null != annotation) {
				return annotation;
			}
			clazz = clazz.getSuperclass();
		}
		return null;
	}

	@Override
	public Point convert(T source) {
		if (source instanceof Point) {
			return (Point) source;
		}
		Point.Builder builder = Point.measurement(measurementName);
		Map<String, Object> fieldsToAdd = new HashMap<>();
		for (ColumnMeta column : columnMap.values()) {
			Object fieldValue = ConverterUtils.readField(source, column.getField());
			if (fieldValue != null) {
				if (column.isTag()) {
					builder.tag(column.getName(), fieldValue.toString());
				} else if (column.isTime()) {
					Long time = 0L;
					if (fieldValue instanceof Date) {
						time = ((Date) fieldValue).getTime();
					} else {
						time = (Long) fieldValue;
					}
					builder.time(time, timeUnit);
				} else {
					fieldsToAdd.put(column.getName(), fieldValue);
				}
			}
		}
		builder.fields(fieldsToAdd);
		return builder.build();
	}

	@Override
	public List<T> convert(QueryResult result) throws RuntimeException {
		List<Map<String, Object>> mapList = convert2Map(result);
		return JSON.parseList(mapList, measurementClass);
	}

	private List<Map<String, Object>> convert2Map(QueryResult results) {
		List<Map<String, Object>> mapList = new ArrayList<>();
		if (results.getResults() != null) {
			for (QueryResult.Result result : results.getResults()) {
				List<QueryResult.Series> series = result.getSeries();
				if (series != null) {
					for (QueryResult.Series sere : series) {
						List<String> columns = sere.getColumns();// 字段名
						List<List<Object>> valuesList = sere.getValues();// 数据集合
						if (columns != null && valuesList != null) {
							for (int i = 0; i < valuesList.size(); i++) {
								List<Object> values = valuesList.get(i);
								Map<String, Object> map = new HashMap<>();
								for (int j = 0; j < values.size(); j++) {
									String column = columns.get(j);
									Object value = values.get(j);
									if (timeColumn != null && column.equals(timeColumn.getName())) {
										if (timeColumn.isNumeric()) {
											map.put(column, TimeUtil.fromInfluxDBTimeFormat(value + ""));
										} else {
											map.put(column, new Date(TimeUtil.fromInfluxDBTimeFormat(value + "")));
										}
									} else {
										map.put(column, value);
									}
								}
								mapList.add(map);
							}
						}
					}
				}
			}
		}
		return mapList;
	}

}
